package cn.whao.guli.order.service.impl;

import cn.whao.guli.order.feign.GuliStockClient;
import cn.whao.guli.order.entity.OrderEntity;
import cn.whao.guli.order.mapper.OrderMapper;
import cn.whao.guli.order.service.OrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

/**
 * ClassName: OrderServiceImpl
 * Package: cn.whao.guli.order.service.impl
 * Description:
 *
 * @Author 王豪
 * @Create 2024/11/26 16:17
 * @Version 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private GuliStockClient guliStockClient;

    @HystrixCommand(fallbackMethod = "saveOrderFallback")  // 指定降级 兜底方法
    @Override
    public boolean saveOrder(String userId, String productId, Integer count) {
        // 创建订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setCount(count);
        orderEntity.setOrderSn(UUID.randomUUID().toString().replace("-", ""));
        orderEntity.setCreateTime(new Date());
        orderEntity.setMoney(new BigDecimal(1000));
        orderEntity.setProductId(productId);
        orderEntity.setUserId(userId);
        orderEntity = orderMapper.save(orderEntity);
        System.out.println(orderEntity);

        // 更新库存

        // 使用HttpClient
        /*try {
            // 初始化客户端
            HttpClient httpClient = HttpClients.createDefault();
            // 设置get请求地址
            HttpGet httpGet = new HttpGet("http://localhost:8083/stock/" + productId + "/" + count);
            HttpResponse response = httpClient.execute(httpGet);
            boolean isSuccess = Boolean.parseBoolean(EntityUtils.toString(response.getEntity()));
            System.out.println("库存更新结果：" + isSuccess);
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        // 使用RestTemplate
        // {1} 占位符，获取可变参数列表的中的第一个
        // GULI-STOCK:从注册中心获取库存服务地址+端口号的服务名
//        Boolean flag = restTemplate.getForObject("http://GULI-STOCK/stock/{1}/{2}", Boolean.class, productId, count);

        // 使用OpenFeign
        Boolean flag = guliStockClient.updateStock(productId, count);
        System.out.println("修改库存结果： " + flag);
        return null != orderEntity;
    }

    public boolean saveOrderFallback(String userId, String productId, Integer count) {
        System.out.println("启用降级方案-saveOrderFallback：userId:" + userId + ", productId：" + productId + ", count：" + count);
        return false;
    }
}
